<template>
  <div class="article-container">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh"
      :success-duration="1500" loosing-text="别扒拉我" :success-text="toastText">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了"
        :error.sync="error" error-text="请求失败，点击重新加载" @load="onLoad">
        <ArticleItem v-for="obj,index in list" :key="index" :article="obj" />
        <!-- <van-cell v-for="obj,index in list" :key="index" :title="obj.title" /> -->
      </van-list>

    </van-pull-refresh>
  </div>
</template>

<script>
import { recommendedChannelApi } from '@/api'
import ArticleItem from '@/components/articleItem'
export default {
  // 组件名称
  name: '',
  // 局部注册的组件
  components: {
    ArticleItem
  },
  // 组件参数 接收来自父组件的数据
  props: {
    channels: {
      type: Object,
      required: true
    }
  },
  // 组件状态值
  data () {
    return {
      params: {
        channel_id: this.channels.id,
        timestamp: Date.now(),
        with_top: 1
      },
      list: [],
      loading: false,
      finished: false,
      error: false,
      isLoading: false,
      toastText: '刷新成功'
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
* 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
*/
  created () {
  },
  /**
* el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
* 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
*/
  mounted () { },
  // 组件方法
  methods: {
    async onLoad () {
      try {
        const { data } = await recommendedChannelApi(this.params)
        // console.log(data)
        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        // 失败测试
        // if (Math.random() > 0.5) {
        //   JSON.parse('adjfjdfd')
        // }
        if (results.length) {
          this.params.timestamp = data.data.pre_timestamp || Date.now()
        } else {
          this.finished = true
        }
      } catch (err) {
        this.loading = false
        this.error = true
      }
    },
    async onRefresh () {
      try {
        const { data } = await recommendedChannelApi(this.params)
        console.log(data)
        const { results } = data.data
        this.list.unshift(...results)
        this.isLoading = false
        // 失败测试
        // if (Math.random() > 0.5) {
        //   JSON.parse('adjfjdfd')
        // }
        this.toastText = '刷新成功'
      } catch (err) {
        // console.log(err)
        this.toastText = '刷新失败'
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-container {
  height: 79vh;
  overflow-y: auto;
}
</style>
